package com.ronglian.register_mini_program.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ronglian.register_mini_program.controller.WXLoginController;
import com.ronglian.register_mini_program.model.*;
import com.ronglian.register_mini_program.result.ResultBody;
import com.ronglian.register_mini_program.service.AccessTokenService;
import com.ronglian.register_mini_program.service.ActivityService;
import com.ronglian.register_mini_program.service.OrderService;
import com.ronglian.register_mini_program.service.UserService;
import com.ronglian.register_mini_program.util.DateUtil;
import com.ronglian.register_mini_program.util.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MySpringTask {
    private Logger logger = LoggerFactory.getLogger(MySpringTask.class);
    @Autowired
    ActivityService activityService;
    @Autowired
    OrderService orderService;
    @Autowired
    AccessTokenService accessTokenService;
    @Autowired
    UserService userService;
    /**
     * spring task，@Scheduled(cron = "0/5 * * * * ? ")即可开启定时任务
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void doTask() {
        //1.获取所有活动，一个小时，判断一下活动的截止时间
        List<RegisterActivityWithBLOBs> registerActivities = activityService.selectAllActivity();
        if (registerActivities != null && registerActivities.size() > 0) {

            for (RegisterActivityWithBLOBs activity : registerActivities) {
                //2.获取当前时间，获取活动的截止时间
                long current_time = System.currentTimeMillis();
                if (activity.getEnd_time() != null) {
                    long end_time = activity.getEnd_time().getTime();
                    if (end_time <= current_time) {
                        //3.判断该活动的状态是否已经失效,如果大于0，就修改该状态，如果等于0就证明已经失效
                        int is_alive = activity.getIs_alive();
                        if (is_alive > 0) {
                            activity.setIs_alive(0);
                            activityService.update(activity);


                            int activity_id = activity.getActivity_id();
                            List<RegisterOrder> orders = orderService.findOrderListWithActivityId(activity_id);
                            if (orders != null && orders.size() > 0) {
                                for (RegisterOrder order : orders) {
//                                    WXLoginController wx = new WXLoginController();
                                    //如果已经失效，就发送微信通知
                                    String appid = "wx40b8e0d1d6ca6b27";
                                    String appSecret = "6f2c00b45cee154e1ce7822aac90f2a5";
                                    //用户id
                                    String touser = order.getOpen_id();
                                    String template_id = "pRCiZGZf9CtdGp8ccH4LXjbEIYevuNpC2qHId3xMquc";
                                    String page = "/page/index/index";

                                    //form_id是小程序端生成的，需要存储给用户，无限生成，在表里面获取
                                    //q七天的时效性和仅仅只能使用一次


                                    String form_id = String.valueOf(System.currentTimeMillis());
                                    List<UserForm> forms = userService.getFormIdListWithOpenId(touser);
                                    if (forms!=null&&forms.size()>0){
                                        for (UserForm form:forms){
                                            //比较是否过期
                                            long now = System.currentTimeMillis();

                                            long before_time = form.getCreate_time()+form.getExpired_in();

                                            int is_used= form.getIs_used();
                                            if (now<before_time&&is_used==0){
                                                form_id = form.getForm_id();
                                                return;
                                            }

                                        }
                                    }else{
                                        return;
                                    }

                                    String activity_name = activity.getActivity_title();
                                    String activity_address = activity.getActivity_postion();
                                    String activity_time = DateUtil.dateToStrLong(activity.getEnd_time());
                                    String activity_mark = "报名已经截止，请知晓！";
                                    try {
//                                        WxUserAccessTokens wxUserAccessTokens = accessTokenService.findByAppid(appid);
//                                        if (wxUserAccessTokens!=null){
//                                            System.out.println("task============="+wxUserAccessTokens.getWx_access_token());
//                                        }
                                        JSONObject jsonObject = sendTemplateMessage(appid, appSecret, touser, template_id, page, form_id, activity_name, activity_address, activity_time, activity_mark);
                                        if (jsonObject != null) {
                                            if (jsonObject.get("errmsg").equals("ok")) {
                                                System.out.println("发送****报名截止*******通知成功！");
                                                System.out.println("定时任务：判断活动的截止时间是否已经到了" + activity.getActivity_title() + activity.getEnd_time());
                                            }else {

                                            }
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }
                            }

                        }
                    }


                }
            }

        }
        logger.info(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "  " + Thread.currentThread().getName());
    }

    public String getWxAccesToken(String appid, String appSecret
    ) {
        try {
            String access_token = "";
            if (!StringUtils.isBlank(appid)) {
                System.out.println("appid不是空哦！！！！！！！"+appid);
                //无则添加 有则比较有效期和修改
                WxUserAccessTokens accessTokens = new WxUserAccessTokens();
                System.out.println("我要验证为什么task传过来的appid查不了"+appid);
                accessTokens = accessTokenService.findByAppid(appid);
                if (accessTokens != null) {
                    long beforeTime = accessTokens.getUpdate_time().getTime();
                    //比较现在的日期增加1.5后的时间>7200*0.75    1.5小时的话还大于access token的生成时间，说明就该换了
                    long nowtime = new Date().getTime();
                    long nowt = System.currentTimeMillis();
                    long beforeTwoHourTime = DateUtil.addSomeHours(1.5).getTime();

                    long interval = beforeTwoHourTime - beforeTime;
                    //7200s=7200*1000ms
                    long standard_interval = (long) (7200 * 0.75 * 1000);
                    boolean bool = interval > standard_interval;
                    System.out.println("access_token是否过期" + bool);
                    if (bool || StringUtils.isBlank(accessTokens.getWx_access_token())) {
                        System.out.println("access_token过期了呀！！！！！！！！");
                        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appSecret;
                        JSONObject jsonObj = HttpClientUtils.httpGet(url);
                        System.out.println(jsonObj);
                        access_token = (String) jsonObj.get("access_token");
                        Integer expires_in = (Integer) jsonObj.get("expires_in");
                        accessTokens.setWx_app_secret(appSecret);
                        accessTokens.setWx_access_token(access_token);
                        accessTokens.setUpdate_time(new Date());
                        accessTokenService.update(accessTokens);
                        accessTokens = accessTokenService.findByAppid(appid);

                    } else {
                        System.out.println("access_token还能用！！！！！！！！");
                        access_token = accessTokens.getWx_access_token();
                    }

                } else {
                    System.out.println("重新获取access_token了！！！！！！！！！");
                    //获取access_token
                    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appSecret;
                    JSONObject jsonObj = HttpClientUtils.httpGet(url);
                    System.out.println(jsonObj);
                    access_token = (String) jsonObj.get("access_token");
                    Integer expires_in = (Integer) jsonObj.get("expires_in");
                    WxUserAccessTokens new_accessTokens = new WxUserAccessTokens();
                    new_accessTokens.setExpires_in(expires_in);
                    new_accessTokens.setWx_access_token(access_token);
                    new_accessTokens.setWx_app_id(appid);
                    new_accessTokens.setWx_app_secret(appSecret);
                    new_accessTokens.setCreate_time(new Date());
                    new_accessTokens.setUpdate_time(new Date());
                    accessTokenService.insert(new_accessTokens);
                }
            }

//        objectMapper.readvalu
            System.out.println("要返回access_token了" + access_token);
            return access_token;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
    public JSONObject sendTemplateMessage(String appid,String appSecret, String touser, String template_id,
            String page, String form_id, String activity_name, String activity_address, String activity_time,
            String activity_mark
    ) throws IOException {

        try {
            String str = "";
            JSONObject jsonObject = null;

            //         //先传appid和appsecret自动生成或传回access_token然后去请求二维码
            System.out.println("发送模板之前的appid==="+appid+"=====appsecret==="+appSecret);
            String accesToken = getWxAccesToken(appid, appSecret);
            System.out.println("Access_token==========" + accesToken);
            if (StringUtils.isNotBlank(accesToken)) {
                System.out.println("发送模板获取token:==========" + accesToken);

                String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + accesToken;
                Map<String, Object> params = new HashMap<>();
                params.put("touser", touser);
                params.put("template_id", template_id);
                params.put("page", page);
                params.put("form_id", form_id);
                Map<String, Object> data = new HashMap<>();
                Map<String, Object> value1 = new HashMap<>();
                Map<String, Object> value2 = new HashMap<>();
                Map<String, Object> value3 = new HashMap<>();
                Map<String, Object> value4 = new HashMap<>();
                value1.put("value", activity_name);
                value2.put("value", activity_address);
                value3.put("value", activity_time);
                value4.put("value", activity_mark);
                data.put("keyword1", value1);
                data.put("keyword2", value2);
                data.put("keyword3", value3);
                data.put("keyword4", value4);
                params.put("data", data);

                CloseableHttpClient httpClient = HttpClientBuilder.create().build();
                System.out.println("touser来了！！！！！！=====" + touser);
                System.out.println("form_id来了！！！！！！=====" + form_id);
                System.out.println("template_id来了！！！！！！=====" + template_id);
                HttpPost httpPost = new HttpPost(url);
                httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
                String body = JSON.toJSONString(params);
                System.out.println("发送模板信息======请求的json数据：" + body);
                StringEntity entity = new StringEntity(body, "UTF-8");
                entity.setContentEncoding("UTF-8");

                httpPost.setEntity(entity);
                HttpResponse response = null;
                try {
                    response = httpClient.execute(httpPost);
                    System.out.println("httpPost请求之后的响应！！！！！！！");
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("失败！！！！！！！！！");
                }
                try {
                    // 读取服务器返回过来的json字符串数
                    str = EntityUtils.toString(response.getEntity(), "UTF-8");
                    System.out.println("读取服务器返回过来的json字符串数======" + str);
                    // 把json字符串转换成json对象
                    jsonObject = JSONObject.parseObject(str);
                    if (jsonObject!=null&&jsonObject.get("errmsg").equals("ok")){

                        System.out.println("模板发送成功！");
                    }else {
                        System.out.println("模板发送失败！原始是"+jsonObject.get("errmsg"));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("发送模板信息失败！");
                }
            }
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送模板信息失败！");
            return null;
        }

    }
}
